package server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import database.dao.WebcamDAO;
import database.manager.DatabaseManager;

public class CamConnection implements Runnable {
	private static boolean		isMovement	= false;
	private static boolean		sendSignal	= false;
	private static WebcamDAO	wbc			= null;

	@SuppressWarnings( "static-access" )
	public CamConnection( WebcamDAO wbc ) {
		this.wbc = wbc;
	}

	@Override
	public void run() {
		int port = Integer.parseInt( DatabaseManager.configFile.getProperty( "CAMPORT" ) );
		String host = DatabaseManager.configFile.getProperty( "CAMHOST" );
		while( true ) {
			try {
				Socket skt = new Socket( host, port );
				System.out.println( "Cameraconnection created" );
				PrintWriter out = new PrintWriter( skt.getOutputStream(), true );
				while( !skt.isClosed() ) {
					if( sendSignal == true ) {
						String newTempEntry = getNewEntry();
						System.out.println( newTempEntry );
						String[] tempEntries = newTempEntry.split( "\\." );
						String newEntry = tempEntries[ 0 ];
						if( isMovement ) {
							out.println( "START " + newEntry );
							System.out.println( "Camera record signal start sent" );
							System.out.println( "START " + newEntry );
							wbc.addVideo( newEntry );
						} else {
							out.println( "STOP" );
							System.out.println( "Camera record signal stop sent" );
						}

						sendSignal = false;
					}
					Thread.sleep( 5000 );
				}
			} catch( UnknownHostException e ) {
				e.printStackTrace();
			} catch( IOException e ) {
				e.printStackTrace();
			} catch( InterruptedException e ) {
				e.printStackTrace();
			}
		}
	}

	private String getNewEntry() {
		return wbc.getNewEntry() + ".mov";
	}

	public static void setMovement( Boolean value ) {
		if( value == isMovement ) {
			return;
		} else {
			sendSignal = true;
			isMovement = value;
		}
	}
}
